package admin_user_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type UserPwdUpdateReq struct {
	OldPwd string `json:"old_pwd" binding:"required"`
	NewPwd string `json:"new_pwd" binding:"required"`
}

func (AdminUserApi) UpdatePwd(c *gin.Context) {
	var req UserPwdUpdateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	value, _ := c.Get(utils.Claims)
	claims := value.(*utils.CustomClaims)
	// 查询用户
	var userModel models.UserModel
	err := global.DB.Take(&userModel, claims.UserID).Error
	if err != nil {
		panic("用户不存在")
	}
	// 校验旧密码
	if !utils.ComparePwd(userModel.Password, req.OldPwd) {
		panic("旧密码输入错误")
	}
	// 设置新密码
	newPwdHash := utils.HashPwd(req.NewPwd)
	err = global.DB.Model(&userModel).Update("password", newPwdHash).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	res.Ok("密码修改成功", true, c)
}
